package models

import (
	"database/sql/driver"
	"encoding/json"
	"fmt"
)

//用于区分应用和api接口
type TypeEnum int64

const (
	APP TypeEnum = iota
	API
	HOST
)

const ApiInfoTableName = "t_api"

type Api struct {
	//表字段
	ID           uint64        `gorm:"primary_key,column:id" json:"id,omitempty" form:"id"`
	AppID        uint64        `gorm:"column:app_id" json:"app_id,omitempty" form:"app_id"`
	AppName      string        `gorm:"column:app_name" json:"app_name,omitempty" form:"app_name"`
	Level        int           `gorm:"column:level" json:"level,omitempty" form:"level"`
	HttpMethod   string        `gorm:"column:http_method" json:"http_method,omitempty" form:"http_method"`
	HttpPath     string        `gorm:"column:http_path" json:"http_path,omitempty" form:"http_path"`
	ZeusMethod   string        `gorm:"column:zeus_method" json:"zeus_method,omitempty" form:"zeus_method"`
	ZeusService  string        `gorm:"column:zeus_service" json:"zeus_service,omitempty" form:"zeus_service"`
	Type         int           `gorm:"column:type" json:"type,omitempty" form:"type"` //0:http 1:zeusserver 2:zeusclient
	DevGroupID   string        `gorm:"column:dev_group_id" json:"dev_group_id,omitempty" form:"dev_group_id"`
	DevGroupName string        `gorm:"column:dev_group_name" json:"dev_group_name,omitempty" form:"dev_group_name"`
	Owner        string        `gorm:"owner" json:"owner,omitempty" form:"owner"`
	DisableGraph *DisableGraph `gorm:"type:json;column:disable_graph" json:"disable_graph"`
	//传输字段
	Query        string              `gorm:"-" json:"query,omitempty" form:"query"` //用于模糊查询
	Owners       []*ApplicationOwner `gorm:"-" json:"owners,omitempty" form:"owners"`
	PageNum      int64               `gorm:"-" json:"page_num" form:"page_num"`
	PageSize     int64               `gorm:"-" json:"page_size" form:"page_size"`
	Method       string              `gorm:"-" json:"method,omitempty" form:"method"`
	TemplateType int                 `gorm:"-" json:"template_type"`  //1:http 2:zeus
	ParentApiID  uint64              `gorm:"-"  json:"parent_api_id"` //zeus客户端对应的服务端id

}

func (Api) TableName() string {
	return ApiInfoTableName
}

func (api Api) GetOwners() []*ApplicationOwner {
	if api.Owner == "" {
		return nil
	}
	var result []*ApplicationOwner
	err := json.Unmarshal([]byte(api.Owner), &result)
	if err != nil {
		return result
	}
	return result
}

type DisableGraph struct {
	GraphID []int `json:"graph_id"`
}

func (s *DisableGraph) Value() (driver.Value, error) {
	return json.Marshal(s)
}

func (s *DisableGraph) Scan(input interface{}) error {
	return json.Unmarshal(input.([]byte), s)
}

func (a *Api) GetMethod() string {
	switch a.Type {
	case 0:
		return fmt.Sprintf("%s:%s", a.HttpMethod, a.HttpPath)
	case 1:
		return fmt.Sprintf("%s:%s", a.ZeusService, a.ZeusMethod)
	case 2:
		return fmt.Sprintf("%s:%s", a.ZeusService, a.ZeusMethod)
	}
	return ""
}
